package cn.yanhu.kuwanapp.user

import android.content.Context
import android.content.Intent
import android.os.Build
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.view.View
import androidx.core.view.isVisible
import androidx.lifecycle.Observer
import cn.woochen.comlib.BaseActivity
import cn.woochen.comlib.util.ActivityUtil
import cn.woochen.comlib.util.OnSingleClickListener
import cn.woochen.comlib.util.UserPref
import cn.woochen.comlib.util.ext.setOnSingleClickListener
import cn.yanhu.kuwanapp.R
import cn.yanhu.kuwanapp.bean.other.WxUserInfoBean
import cn.yanhu.kuwanapp.bean.response.RespWxLoginBean
import cn.yanhu.kuwanapp.databinding.ActivityPhoneLoginBinding
import cn.yanhu.kuwanapp.home.MainActivity
import cn.yanhu.kuwanapp.utils.constans.Constants
import cn.yanhu.kuwanapp.utils.ext.logcom
import cn.yanhu.kuwanapp.utils.ext.parseState
import cn.yanhu.kuwanapp.utils.ext.parseState2
import cn.yanhu.kuwanapp.utils.ext.showToast
import com.google.gson.Gson
import com.jakewharton.rxbinding4.widget.textChanges
import com.tbruyelle.rxpermissions3.RxPermissions
import io.reactivex.rxjava3.core.Observable
import io.reactivex.rxjava3.functions.BiFunction
import java.io.Serializable

/**
 * 类描述：手机号登录
 * @author：woochen
 * create at：2021/7/25 3:54 PM
 */
class PhoneLoginActivity : BaseActivity<ActivityPhoneLoginBinding, UserViewModel>(),
    OnSingleClickListener {

    private var mToken by UserPref(Constants.USER_TOKEN, "")
    private var mUserId by UserPref(Constants.USER_ID, "")

    override fun setContentView(): Int = R.layout.activity_phone_login

    override fun initData() {
        setStatusBarStyle(false)
        if (!mTitle.isNullOrBlank()){
            mBinding.tvTitle.text = mTitle
        }
    }

    override fun registerNecessaryObserver() {
        super.registerNecessaryObserver()
        //验证码
        mViewModel.sendCodeInfo.observe(this, Observer { it ->
            parseState2(it, {
                showToast("验证码已发送")
            })
        })
        //手机号验证码登录
        mViewModel.phoneLoginInfo.observe(this, Observer { it ->
            parseState(it, {
                showToast("登录成功!")
                ActivityUtil.finishAllActivity()
                mToken = it.token
                mUserId = it.userId
                MainActivity.start(mContext)
                back()
            })
        })
    }

    override fun initListener() {
        val phoneObservable = mBinding.etPhone.textChanges()
        val codeObservable = mBinding.etCode.textChanges()
        Observable.combineLatest(phoneObservable,
            codeObservable,
            BiFunction<CharSequence, CharSequence, Boolean> { t1, t2 ->
                mBinding.ivClear.isVisible = t1.isNotBlank()
                t1.length == 11 && t2.isNotBlank()
            }).subscribe {
            mBinding.tvLogin.isEnabled = it
        }
        mBinding.ivClear.setOnSingleClickListener(this, 0)
        mBinding.tvLogin.setOnSingleClickListener(this)
        mBinding.tvSendCode.setOnSingleClickListener(this)
    }

    private val mTitle by lazy {
        intent.getStringExtra(EXTRA_TITLE)
    }

    private val mWxUserInfo by lazy {
        intent.getStringExtra(EXTRA_WX_USERINFO)?:""
    }

    companion object {
        private const val EXTRA_TITLE = "extra_title"
        private const val EXTRA_WX_USERINFO = "extra_wx_userinfo"
        fun start(context: Context, title: String = "",wxUserInfo:String = "") {
            val intent = Intent(context, PhoneLoginActivity::class.java)
            intent.putExtra(EXTRA_TITLE, title)
            intent.putExtra(EXTRA_WX_USERINFO, wxUserInfo)
            context.startActivity(intent)
        }
    }

    override fun onSingleClick(v: View?) {
        when (v) {
            mBinding.ivClear -> { //清除输入框
                mBinding.etPhone.setText("")
            }
            mBinding.tvSendCode -> { //发送验证码
                val phone = mBinding.etPhone.text.toString()
                if (phone.length != 11) {
                    showToast("请输入正确的手机号")
                    return
                }
                mBinding.tvSendCode.start()
                mViewModel.sendCode(phone)
            }
            mBinding.tvLogin -> { //登录
                val phone = mBinding.etPhone.text.toString()
                val code = mBinding.etCode.text.toString()
                if (phone.length != 11) {
                    showToast("请输入正确的手机号")
                    return
                }
                if (code.isBlank()) {
                    showToast("验证码错误!")
                    return
                }
                mViewModel.phoneLogin(phone, code,mWxUserInfo)
            }

        }
    }
}